<!-- 场地信息总览页面 -->
<template>
  <div class="page">
    <div class="header-actions">
      <el-button type="primary" @click="handleAdd" :icon="Plus">新增场馆</el-button>
    </div>
    <el-table
      :data="tableData"
      style="width: 100%"
      :default-sort="{ prop: 'id', order: 'ascending' }"
    >
      <el-table-column
        prop="venueName"
        label="场馆名称"
      ></el-table-column>
      <el-table-column
        prop="address"
        label="地址"
      ></el-table-column>
      <el-table-column
        prop="capacity"
        label="可容纳人数"
        sortable
      ></el-table-column>
      <el-table-column
        prop="status"
        label="当前状态"
        sortable
      >
        <template #default="scope">

          <el-tag
            :type="getTagType(scope.row.status)"
            effect="light"
            round
          >
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(scope.row)">修改</el-button>
          <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增场馆对话框 -->
    <el-dialog 
      v-model="addDialogVisible" 
      title="新增场馆" 
      width="45%" 
      destroy-on-close
      top="5vh"
      class="venue-dialog">
      <div class="dialog-header-divider"></div>
      <div class="form-container">
        <el-form 
          :model="venueForm" 
          :rules="rules" 
          ref="venueFormRef" 
          label-width="110px" 
          class="venue-form"
          label-position="left">
          <el-form-item label="场馆名称" prop="venueName">
            <el-input 
              v-model="venueForm.venueName" 
              placeholder="请输入场馆名称"
              prefix-icon="Position"
            ></el-input>
          </el-form-item>
          
          <el-form-item label="地址" prop="address">
            <el-autocomplete
              v-model="venueForm.address"
              :fetch-suggestions="queryAddressSearch"
              placeholder="请输入或选择地址"
              style="width: 100%"
              prefix-icon="Location"
            ></el-autocomplete>
          </el-form-item>
          
          <el-form-item label="可容纳人数" prop="capacity">
            <el-input 
              v-model.number="venueForm.capacity" 
              type="number" 
              placeholder="请输入可容纳人数"
              prefix-icon="User"
            ></el-input>
          </el-form-item>
          
          <el-form-item label="当前状态" prop="status">
            <el-select 
              v-model="venueForm.status" 
              placeholder="请选择状态" 
              style="width: 100%"
              prefix-icon="Flag">
              <el-option 
                v-for="item in stateOptions" 
                :key="item" 
                :label="item" 
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false" :icon="Close">取消</el-button>
          <el-button type="primary" @click="submitVenueForm('venueFormRef')" :icon="Check">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改场馆对话框 -->
    <el-dialog 
      v-model="editDialogVisible" 
      title="修改场馆信息" 
      width="45%" 
      destroy-on-close
      top="5vh"
      class="venue-dialog">
      <div class="dialog-header-divider"></div>
      <div class="form-container">
        <el-form 
          :model="venueForm" 
          :rules="rules" 
          ref="editFormRef" 
          label-width="110px" 
          class="venue-form"
          label-position="left">
          <el-form-item label="场馆名称" prop="venueName">
            <el-input 
              v-model="venueForm.venueName" 
              placeholder="请输入场馆名称"
              prefix-icon="Position"
            ></el-input>
          </el-form-item>
          
          <el-form-item label="地址" prop="address">
            <el-autocomplete
              v-model="venueForm.address"
              :fetch-suggestions="queryAddressSearch"
              placeholder="请输入或选择地址"
              style="width: 100%"
              prefix-icon="Location"
            ></el-autocomplete>
          </el-form-item>
          
          <el-form-item label="可容纳人数" prop="capacity">
            <el-input 
              v-model.number="venueForm.capacity" 
              type="number" 
              placeholder="请输入可容纳人数"
              prefix-icon="User"
            ></el-input>
          </el-form-item>
          
          <el-form-item label="当前状态" prop="status">
            <el-select 
              v-model="venueForm.status" 
              placeholder="请选择状态" 
              style="width: 100%"
              prefix-icon="Flag">
              <el-option 
                v-for="item in stateOptions" 
                :key="item" 
                :label="item" 
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false" :icon="Close">取消</el-button>
          <el-button type="primary" @click="updateVenue('editFormRef')" :icon="Check">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style>
  .venue-management {
    padding: 20px;
  }

  .header-actions {
    margin-bottom: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .venue-form .el-form-item__label {
    font-weight: bold;
    color: #303133;
  }

  .venue-form .el-input-number {
    width: 100%;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding-top: 10px;
  }
  
  .venue-dialog .el-dialog__header {
    margin-right: 0;
    text-align: center;
    padding: 15px 20px 5px;
  }
  
  .venue-dialog .el-dialog__body {
    padding: 0px 20px 20px;
  }
  
  .venue-dialog .el-dialog__title {
    font-size: 18px;
    font-weight: bold;
    color: #409EFF;
  }
  
  .dialog-header-divider {
    height: 1px;
    background-color: #EBEEF5;
    margin-bottom: 15px;
  }
  
  .venue-form .el-input__inner,
  .venue-form .el-select .el-input__inner,
  .venue-form .el-autocomplete .el-input__inner {
    border-radius: 4px;
    height: 36px;
  }

  .venue-form .el-form-item {
    margin-bottom: 16px;
  }
  
  .form-container {
    max-width: 500px;
    margin: 0 auto;
  }
</style>

<script>
  import axios from 'axios'
  import request from '@/utils/request'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import { ref } from 'vue'
  import { 
    Plus, Edit, Delete, 
    Position, Location, User, 
    Flag, Close, Check 
  } from '@element-plus/icons-vue'
  
  export default {
    setup() {
      const tableData = ref([])
      const addDialogVisible = ref(false)
      const editDialogVisible = ref(false)
      const venueForm = ref({
        venueName: '',
        address: '',
        capacity: 0,
        status: ''
      })
      const stateOptions = ref(['维护中', '筹备中', '使用中', '空闲', '已废弃'])
      const rules = ref({
        venueName: [
          { required: true, message: '请输入场馆名称', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入或选择地址', trigger: 'blur' }
        ],
        capacity: [
          { required: true, message: '请输入可容纳人数', trigger: 'blur' },
          { type: 'number', min: 1, message: '可容纳人数必须大于 0', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择当前状态', trigger: 'change' }
        ]
      })
      const venueFormRef = ref(null)
      const editFormRef = ref(null)

      const getVenueInfo = () => {
        request.get('/getVenueInfo').then(res => {
          if (res.data.code === 200) {
            console.log(res)
            tableData.value = res.data.data
          } else {
            ElMessage.error('获取场馆信息失败')
          }
        }).catch(err => {
          console.error('获取场馆信息失败:', err)
          ElMessage.error('获取场馆信息失败')
        })
      }

      const handleAdd = () => {
        venueForm.value = {
          venueName: '',
          address: '',
          capacity: 0,
          status: ''
        }
        addDialogVisible.value = true
        if (venueFormRef.value) {
          venueFormRef.value.resetFields()
        }
      }

      const submitVenueForm = (formRef) => {
        venueFormRef.value.validate(valid => {
          if (!valid) {
            ElMessage.warning('请完善表单信息')
            return
          }
          
          const isVenueExists = tableData.value.some(venue => venue.venueName === venueForm.value.venueName)
          if (isVenueExists) {
            ElMessage.warning(`场馆"${venueForm.value.venueName}"已存在，不能重复添加`)
            return
          }

          request.post('/addVenue', venueForm.value).then(res => {
            if (res.data.code === 200) {
              ElMessage.success('新增场馆成功')
              addDialogVisible.value = false
              getVenueInfo()
            } else {
              ElMessage.error('新增场馆失败')
            }
          }).catch(err => {
            console.error('新增场馆失败:', err)
            ElMessage.error('新增场馆失败')
          })
        })
      }

      const handleEdit = (row) => {
        venueForm.value = { ...row }
        editDialogVisible.value = true
        if (editFormRef.value) {
          editFormRef.value.resetFields()
        }
      }

      const updateVenue = (formRef) => {
        editFormRef.value.validate(valid => {
          if (!valid) {
            ElMessage.warning('请完善表单信息')
            return
          }

          request.put(`/updateVenue/${venueForm.value.id}`, venueForm.value).then(res => {
            if (res.data.code === 200) {
              ElMessage.success('修改场馆信息成功')
              editDialogVisible.value = false
              getVenueInfo()
            } else {
              ElMessage.error('修改场馆信息失败')
            }
          }).catch(err => {
            console.error('修改场馆信息失败:', err)
            ElMessage.error('修改场馆信息失败')
          })
        })
      }

      const handleDelete = (row) => {
        ElMessageBox.confirm(
          `确定要删除场馆 "${row.venueName}" 吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          request.delete(`/deleteVenue/${row.id}`).then(res => {
            if (res.data.code === 200) {
              ElMessage.success('删除场馆成功')
              getVenueInfo()
            } else {
              ElMessage.error('删除场馆失败')
            }
          }).catch(err => {
            console.error('删除场馆失败:', err)
            ElMessage.error('删除场馆失败')
          })
        }).catch(() => {
          ElMessage.info('已取消删除')
        })
      }
      
      const queryAddressSearch = (queryString, cb) => {
        // 这里可以实现地址搜索逻辑
        cb([])
      }

      // 根据状态返回对应的 tag 类型
      const getTagType = (state) => {
        if (['维护中', '筹备中', '使用中'].includes(state)) {
          return 'warning'
        } else if (state === '空闲') {
          return 'success'
        } else if (state === '已废弃') {
          return 'info'
        }
        return 'default'
      }

      getVenueInfo()

      return {
        tableData,
        addDialogVisible,
        editDialogVisible,
        venueForm,
        stateOptions,
        rules,
        venueFormRef,
        editFormRef,
        Plus, Edit, Delete, 
        Position, Location, User, 
        Flag, Close, Check,
        handleAdd,
        submitVenueForm,
        handleEdit,
        updateVenue,
        handleDelete,
        queryAddressSearch,
        getTagType
      }
    }
  }
</script>